package cn.fatgod.learn.thymeleaf.template;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;

import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TemplateManager {
    private final static String SEPARATOR = FileSystems.getDefault().getSeparator();
    private final static Map<String, String> templateMap = new ConcurrentHashMap<>();
    private final static String BUM_NAME = "BUM";
    private final static String ASSET = "asset";

    static {
        templateMap.put(BUM_NAME, StrUtil.EMPTY);
    }

    /**
     * 根据模版名称获取模版内容（字符串内容）
     * @param templateName 模版名称
     * @return 模版内容
     */
    public static String getTemplateContent(String templateName) {
        if (StrUtil.isBlank(templateName)) {
            return templateMap.get(BUM_NAME);
        }
        String content = templateMap.get(templateName);
        if (StrUtil.isNotBlank(content)) {
            return content;
        }
        synchronized (TemplateManager.class) {
            String newContent = templateMap.get(templateName);
            if (StrUtil.isNotBlank(newContent)) {
                return newContent;
            }
            String ctt = buildContent(templateName);
            templateMap.put(templateName, ctt);
            return ctt;
        }
    }

    /**
     * 构建模版内容
     * @param name 模版名称
     * @return 模版内容
     */
    private static String buildContent(String name) {
        String assetPath = TemplateManager.class.getPackage().getName().replaceAll("\\.", SEPARATOR)
                + SEPARATOR + ASSET;
        return ResourceUtil.getResourceObj(assetPath + SEPARATOR + name).readStr(StandardCharsets.UTF_8);
    }
}
